package com.zxzw.scanningin.http
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 存放Retrofit对象的map集合
 */
private val clientMap = mutableMapOf<String, Retrofit>()
private val downloadClientMap = mutableMapOf<String, Retrofit>()

/**
 * 创建获取Retrofit对象
 */
fun getRetrofit(baseUrl: String): Retrofit {
    return if (clientMap.containsKey(baseUrl)) {
        clientMap[baseUrl]!!
    } else {
        clientMap[baseUrl] = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(getHttpClient())
            .baseUrl(baseUrl)
            .build()
        clientMap[baseUrl]!!
    }
}

fun getDownloadRetrofit(baseUrl: String): Retrofit {
    return if (downloadClientMap.containsKey(baseUrl)) {
        downloadClientMap[baseUrl]!!
    } else {
        downloadClientMap[baseUrl] = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(getHttpClient())
            .baseUrl(baseUrl)
            .build()
        downloadClientMap[baseUrl]!!
    }
}

private fun getHttpClient(): OkHttpClient = OkHttpClient.Builder()
    .connectTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(30, TimeUnit.SECONDS)
    .callTimeout(0, TimeUnit.SECONDS)
    .readTimeout(0, TimeUnit.SECONDS)
//    .addInterceptor(HeaderInterceptor())
    .addInterceptor(LogcatInterceptor())
    .build()